package com.zuiacsn.forum.controller;

import com.zuiacsn.forum.common.AppResult;
import com.zuiacsn.forum.common.ResultCode;
import com.zuiacsn.forum.config.AppConfig;
import com.zuiacsn.forum.exception.ApplicationException;
import com.zuiacsn.forum.model.User;
import com.zuiacsn.forum.service.IUserService;
import com.zuiacsn.forum.utils.MD5Util;
import com.zuiacsn.forum.utils.StringUtil;
import com.zuiacsn.forum.utils.UUIDUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@Api(tags = "用户接口")
@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {

    @Autowired
    IUserService userService;

    @PostMapping("/register")
    @ApiOperation("注册")
    public AppResult register(@ApiParam("用户名") @RequestParam("username") @NonNull String username,
                              @ApiParam("昵称") @RequestParam("nickname") @NonNull String nickname,
                              @ApiParam("密码") @RequestParam("password") @NonNull String password,
                              @ApiParam("重复密码") @RequestParam("passwordRepeat") @NonNull String passwordRepeat){
        /*if(StringUtil.isEmpty(username) || StringUtil.isEmpty(nickname) || StringUtil.isEmpty(password)
                || StringUtil.isEmpty(passwordRepeat)){

        }*/
        // 校验密码和重复密码是否相等
        if(!passwordRepeat.equals(password)){
            log.warn(ResultCode.FAILED_TWO_PWD_NOT_SAME.toString());
            return AppResult.failed(ResultCode.FAILED_TWO_PWD_NOT_SAME.toString());
        }

        // 准备数据
        User user = new User();
        user.setUsername(username);
        user.setNickname(nickname);

        // 生成盐
        String salt = UUIDUtil.UUID_32();
        // 生成密文
        String password_salt = MD5Util.md5Salt(password, salt);
        user.setPassword(password_salt);
        user.setSalt(salt);


        userService.createNormalUser(user);
        return AppResult.success();
    }

    @ApiOperation("用户登录")
    @PostMapping("/login")
    public AppResult login(HttpServletRequest request ,
                           @ApiParam("用户名") @RequestParam("username") @NonNull String username,
                           @ApiParam("密码") @RequestParam("password")@NonNull String password){
        // 1.调用登录方法,返回user对象
        User user = userService.login(username,password);
        // 2.如果登录成功,将user设置到session作用域中
        HttpSession session = request.getSession(true);
        session.setAttribute(AppConfig.USER_SESSION,user);
        // 3.返回结果
        return AppResult.success();
    }

    @ApiOperation("获取用户信息")
    @GetMapping("/info")
    public AppResult getUserInfo(HttpServletRequest request,
                                 @ApiParam("用户id") @RequestParam(value="id",required = false) Long id){
        User user = null;

        if(id == null){
            // 1.如果id为空,从session中获取用户信息
            HttpSession session = request.getSession(false); // 没有session,不创建
            user = (User) session.getAttribute(AppConfig.USER_SESSION);
        }else{
            // 2.如果id不为空,从数据库中查询用户信息
            user = userService.selectById(id);
        }

        if(user == null){
            return AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS);
        }

        return AppResult.success(user);
    }


    @ApiOperation("用户退出登录")
    @GetMapping("/logout")
    public AppResult logout(HttpServletRequest request){

        // 获取session对象
        HttpSession session = request.getSession(false);
        if(session != null){
            // 直接销毁session对象
            log.info("退出成功!");
            session.invalidate();
        }
        return AppResult.success("退出成功!");
    }

    @ApiOperation("修改用户信息")
    @PostMapping("/modifyInfo")
    public AppResult modifyInfo(HttpServletRequest request,
                                @ApiParam("用户名") @RequestParam(value="username",required = false)String username,
                                @ApiParam("昵称") @RequestParam(value="nickname",required = false)String nickname,
                                @ApiParam("邮箱") @RequestParam(value="email",required = false)String email,
                                @ApiParam("性别") @RequestParam(value="gender",required = false)Byte gender,
                                @ApiParam("电话号码") @RequestParam(value="phoneNum",required = false)String phoneNum,
                                @ApiParam("自我评价") @RequestParam(value="remark",required = false)String remark){
        // @sessionAttribute(AppConfig.USER_SESSION)
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);

        // 对参数做非空校验,全部为空返回错误信息
        if(StringUtil.isEmpty(username) && StringUtil.isEmpty(nickname)&&
                StringUtil.isEmpty(email)&& StringUtil.isEmpty(phoneNum)&& StringUtil.isEmpty(remark) && gender == null){
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        // 封装对象
        User updateUser = new User();
        updateUser.setId(user.getId());
        updateUser.setUsername(username);
        updateUser.setNickname(nickname);
        updateUser.setEmail(email);
        updateUser.setPhoneNum(phoneNum);
        updateUser.setGender(gender);
        updateUser.setRemark(remark);
        // 调用service中的方法
        userService.modifyInfo(updateUser);
        // 返回结果
        return AppResult.success();
    }

    @ApiOperation("修改用户密码")
    @PostMapping("/modifyPwd")
    public AppResult modifyPwd(HttpServletRequest request,
                               @ApiParam("新密码") @RequestParam(value="newPassword",required = false) @NonNull String newPassword,
                               @ApiParam("老密码") @RequestParam(value="oldPassword",required = false) @NonNull String oldPassword,
                               @ApiParam("重复密码") @RequestParam(value="passwordRepeat",required = false) @NonNull String passwordRepeat){
        // 校验新密码和重复密码是否相同
        if(!newPassword.equals(passwordRepeat)){
            log.warn(ResultCode.FAILED_TWO_PWD_NOT_SAME.toString());
            return AppResult.failed(ResultCode.FAILED_TWO_PWD_NOT_SAME);
        }
        // 从session中获取当前登录用户的id
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);

        // 调用serivce方法
        userService.modifyPwd(user.getId(),newPassword,oldPassword);

        //返回结果
        return AppResult.success();
    }




}
